package pers.cocoadel.springcloud.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import pers.cocoadel.springcloud.entities.CommonResult;
import pers.cocoadel.springcloud.entities.Payment;

import java.net.URI;

import static org.springframework.http.HttpMethod.GET;


/**
 * @author rwby
 */
@RestController
@RequestMapping("/consumer")
public class OrderController
{
    //    private final static String PAYMENT_URL = "http://localhost:8081/payment";
//    private final static String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE/payment";
    private final static String PAYMENT_URL = "http://payment8083/payment";

    private final RestTemplate restTemplate;

    @Autowired
    public OrderController(RestTemplate restTemplate)
    {
        this.restTemplate = restTemplate;
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getById(@PathVariable("id") Long id)
    {
        ParameterizedTypeReference<CommonResult<Payment>> typeReference =
                new ParameterizedTypeReference<CommonResult<Payment>>()
                {
                };
        return restTemplate
                .exchange(PAYMENT_URL + "/get/" + id, GET, null, typeReference)
                .getBody();
    }

    @PostMapping("/payment/create")
    public CommonResult<Payment> create(@RequestBody Payment payment)
    {
        ParameterizedTypeReference<CommonResult<Payment>> typeReference =
                new ParameterizedTypeReference<CommonResult<Payment>>()
                {
                };
        URI uri = UriComponentsBuilder.fromUriString(PAYMENT_URL + "/create").build().toUri();
        RequestEntity<Payment> requestEntity = RequestEntity.post(uri)
                .accept(MediaType.APPLICATION_JSON)
                .header("Content-Type", "application/json")
                .body(payment);
        return restTemplate
                .exchange(requestEntity, typeReference)
                .getBody();
    }

    @GetMapping("/payment/getForEntity/{id}")
    public CommonResult<Payment> getForEntityById(@PathVariable("id") Long id)
    {
        ResponseEntity<CommonResult> responseEntity = restTemplate.getForEntity(PAYMENT_URL + "/get/" + id,
                CommonResult.class);
        System.out.println("responseEntity.getStatusCode().value()： "+ responseEntity.getStatusCode().value());
        if (responseEntity.getStatusCode().is2xxSuccessful())
        {
            return responseEntity.getBody();
        }
        else
        {
            return new CommonResult<>(404,"获取消息失败",null);
        }
    }

}
